from django.shortcuts import render
import logging
import random
import string
from .models import Track, userInfo, PlayRecord
from rest_framework.parsers import JSONParser
from rest_framework.decorators import api_view
from django.http import HttpResponse, JsonResponse  # 返回状态
from django.shortcuts import render
from rest_framework.parsers import JSONParser
from rest_framework.decorators import api_view
from django.http import HttpResponse, JsonResponse
# 分页所需的包
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
from django.core.signing import Signer  # 签名
from django.core.cache import cache  # 缓存
from datetime import timedelta  # 超时


# Create your views here.
def creat_token(name):
    randomstr = ''.join(random.choices(string.ascii_letters, k=8))
    token = Signer().sign(randomstr + name)
    cache.set(f"test_{name}", token, timeout=timedelta(minutes=100).total_seconds())
    return token


def check_token(request):
    reqtoken = request.META.get('HTTP_TOKEN')
    if reqtoken is None:
        return False, 'xx'
    try:
        untoken = Signer().unsign(reqtoken)
    except:
        return False, 'xx'
    name = untoken[8:]
    cachetoken = cache.get(f"test_{name}")
    if cachetoken is None:
        return False, 'xx'
    return True, name


# 用户登录
@api_view(['post'])
def login(request):
    data = JSONParser().parse(request)
    name = data.get('name')
    password = data.get('password')
    if userInfo.objects.filter(username=name).exists() is False:
        return JsonResponse({'code': 400, 'msg': "用户名不存在"})
    obj = userInfo.objects.get(username=name)
    if obj.password != password:
        return JsonResponse({'code': 400, 'msg': "密码错误"})
    token = creat_token(name)
    return JsonResponse({
        'code': 200,
        'msg': "登录成功",
        'token': token
    })


def is_empty(n):
    return n is None or str(n).strip() == ''


# 音乐点播接口
@api_view(['PUT'])
def tracks_play(request):
    track_id = request.GET.get('track_id')
    user_id = request.GET.get('user_id')
    flag, namae = check_token(request)
    if flag is False:
        return JsonResponse({'code': 400, 'msg': "请先登录"})
    if is_empty(track_id) or is_empty(user_id):
        return JsonResponse({'code': 400, 'msg': "必填项不能为空"})
    return JsonResponse({
        'code': 200,
        'msg': "点播成功",
    })


@api_view(['get'])
def myplays(request):
    page = request.GET.get('page')
    pagesize = request.GET.get('pagesize')
    flag, namae = check_token(request)
    if flag is False:
        return JsonResponse({'code': 404, 'msg': "请先登录"})
    alldata = PlayRecord.objects.filter().values()
    pageobjall = Paginator(alldata, pagesize)
    try:
        singlepageobj = pageobjall.page(page)
    except EmptyPage:
        singlepageobj = pageobjall.page(pageobjall.num_pages)
    except PageNotAnInteger:
        singlepageobj = pageobjall.page(1)
    lis = []

    for item in singlepageobj.object_list:
        logging.info(item)
        lis.append({
            '曲目名称': item.get('trackid_id'),
            '用户名': item.get('user_id'),
            '播放次数': item.get('play_times'),
            '播放日期': item.get('play_date'),
        })

    return JsonResponse({
        'code': 200,
        'msg': '查询成功',
        'data': lis,
        'items': alldata.count()
    })
